﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Controls;
using System.ComponentModel;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Unity;
using Interfaces;

namespace ViewModels
{
    public class ChartViewModel : BindableBase, IChartViewModel
    {
        public IChartModel ChartModel { get { return _chartModel; } private set { SetProperty(ref _chartModel, value); } }
        public IList<string> Selections { get { return _selections; } }
        public string Selection { get { return _selection; } private set { OnChangeChart(value); } }
        public ICommand RefreshCommand { get { return _refreshCommand == null ? _refreshCommand = new DelegateCommand<string>(OnRefresh) : _refreshCommand; } }

        private IChartModel _chartModel;
        private IList<string> _selections = new List<string>() { "ChartCandlestickView", "ChartMovingAverageView" };
        private ICommand _refreshCommand;
        private string _selection;
        private readonly IUnityContainer _container;
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAgregator;
        private readonly ILoggerFacade _logger;

        public ChartViewModel(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAgregator, ILoggerFacade logger, IChartModel chartModel)
        {
            _logger = logger;
            _container = container;
            _regionManager = regionManager;
            _eventAgregator = eventAgregator;
            _chartModel = chartModel; 
            _selection = _selections.First();
        }

        private void OnRefresh(string ticker)
        {
            try
            {
                _chartModel.GetService();
                _eventAgregator.GetEvent<ChartResfreshEvent>().Publish(ticker);
            }
            catch (Exception e)
            {
                _logger.Log(e.Message, Category.Exception, Priority.High);
            }
        }

        private void OnChangeChart(string selection)
        {
            try
            {
                if (selection.Equals(_selection)) return;

                var region = _regionManager.Regions["ChartRegion"];
                foreach (var view in region.Views)
                    region.Remove(view);

                _regionManager.AddToRegion("ChartRegion", (IView)_container.Resolve(typeof(IView), _selection = selection)); 

            }
            catch (Exception e)
            {
                _logger.Log(e.Message, Category.Exception, Priority.High);
            }
        }
    }
}
